<?php

class MapDb
{
    private static $uuidName;
    private static $uuidValue;
    private static $dbName;
    private static $tableName;
    private static $mapPrefix;

    public static function beginTransaction($key){
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;
        return $dbHandle->begin();
    }

    public static function commitTransaction($key){
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;
        return $dbHandle->commit();
    }

    public static function rollbackTransaction($key){
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;
        return $dbHandle->rollback();
    }

    public static function fetch($key, $orderBy)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $fields =   NULL;
        $dbSql  =   self::getQuerySentence($fields, $orderBy);
        $result =   $dbHandle->getOneResult($dbSql);

        return  $result;
    }/*}}}*/

    public static function fetchByBodyid($code, $bodyId, $fields, $uuidName)/*{{{*/
    {
        $dbHandle   =   self::mdHandleByBodyid($code, $bodyId, $uuidName);
        if (empty($dbHandle))   return  FALSE;

        $dbSql  =   self::getQuerySentenceByBodyid($fields);
        $result =   $dbHandle->getOneResult($dbSql);

        return  $result;
    }/*}}}*/

    public static function fetchByBodyidWithId($code, $bodyId, $fields, $uuidName)/*{{{*/
    {
        $dbHandle   =   self::mdHandleByBodyid($code, $bodyId, $uuidName);
        if (empty($dbHandle))   return  FALSE;

        $dbSql  =   self::getQuerySentenceByBodyidWithId($fields);
        $result =   $dbHandle->getOneResult($dbSql);

        return  $result;
    }
    
    public static function fetchMany($key, $fields, $orderBy, $start, $len)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getQuerySentence($fields, $orderBy, $start, $len);
        $result     =   $dbHandle->getManyResult($dbSql);

        return  $result;
    }/*}}}*/

    public static function fetchCondition($key, $where, $orderBy)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $fields =   NULL;
        $dbSql  =   self::getConditionQuerySentence($fields, $where, $orderBy);
        $result =   $dbHandle->getOneResult($dbSql);

        return  $result;
    }/*}}}*/

    public static function fetchConditionMany($key, $fields, $where, $orderBy, $start, $len)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getConditionQuerySentence($fields, $where, $orderBy, $start, $len);
        $result     =   $dbHandle->getManyResult($dbSql);

        return  $result;
    }/*}}}*/
    
    public static function insertOrUpdate($key, $where)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;
        
        $fields    =  array();
        $values    =  array();
        $updates   =  array();
        
        foreach ($where as $field => $list){
            if($list == '' || empty($list)) continue;
            $fields[] = ' `'. $field. '` ';
            $values[] = "'". $list . "'";
            $updates[]= $field."='".$list."'";
        }
        $fieldString    =   ' ('. implode(',', $fields). ') ';
        $valueString    =   ' ('. implode(',', $values). ') ';
        $updateString   =   implode(',', $updates);
        
        $dbSql = 'INSERT INTO '. self::$dbName. '.'. self::$tableName . $fieldString .' VALUES '. $valueString .' ON DUPLICATE KEY UPDATE '.$updateString;
    
        $result     =   $dbHandle->dbExec($dbSql);
        
        if (empty($result)) return  $result;
        $result     =   $dbHandle->getAffectedRows();
        
        return  $result;
    }/*}}}*/
    
    public static function fetchCountRow($key, $where)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getCountRowSentence($where);
        $result     =   $dbHandle->getOneResult($dbSql);
        if (empty($result['num']))  return  0;
        return  $result['num'];
    }/*}}}*/

    public static function insert($key, $value = NULL)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getInsertSentence($value);
        $result     =   $dbHandle->dbExec($dbSql);

        if (empty($result)) return  $result;
        $result     =   $dbHandle->getInsertId();

        return  $result;
    }/*}}}*/
    
    public static function update($key, $value)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getUpdateSentence($value);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function updateCondition($key, $value, $where)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getUpdateConditionSentence($value, $where);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function complexUpdate($key, $value)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getUpdateComplexSentence($value);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function remove($key)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getRemoveSentence();
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function removeCondition($key, $where)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getRemoveConditionSentence($where);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function execDbSentence($key, $dbSql)/*{{{*/
    {
        if (empty($dbSql))      return  FALSE;

        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $result     =   $dbHandle->dbExec($dbSql);
        return  $result;
    }/*}}}*/

    public static function execDbSentenceByClient($key, $dbSql)/*{{{*/
    {
        if (empty($dbSql))      return  FALSE;

        $dbHandle   =   self::mdHandleByClient($key);
        if (empty($dbHandle))   return  FALSE;

        $result     =   $dbHandle->dbExec($dbSql);
        return  $result;
    }/*}}}*/

    public static function fetchDbSentence($key, $dbSql, $rows = 1)/*{{{*/
    {
        if (empty($dbSql))      return  FALSE;

        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        if (1   ==  $rows)  $result =   $dbHandle->getOneResult($dbSql);
        else                $result =   $dbHandle->getManyResult($dbSql);

        return  $result;
    }/*}}}*/

    public static function fetchDbSentenceByClient($key, $dbSql, $rows = 1)/*{{{*/
    {
        if (empty($dbSql))      return  FALSE;

        $dbHandle   =   self::mdHandleByClient($key);
        if (empty($dbHandle))   return  FALSE;

        if (1   ==  $rows)  $result =   $dbHandle->getOneResult($dbSql);
        else                $result =   $dbHandle->getManyResult($dbSql);

        return  $result;
    }/*}}}*/

    /**
     * For modify UserBonus fields (not inlcude mood)
     */
    public static function limitUpdate($key, $value)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getLimitUpdateSentence($value);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function limitConditionUpdate($key, $value, $where)/*{{{*/
    {
        if (empty($where))  return  self::limitUpdate($key, $value);

        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getLimitConditionUpdateSentence($value, $where);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

	public static function changeNumValueAdd($key, $value, $where)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getSentenceNumValueAdd($value, $where);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/
    /**
     * For modify UserBonus->mood!
     * @param   String  $key    xxprefix/uid
     * @param   Array   $value  array('mood' => num)
     * @return  Bool
     */
    public static function changeNumBetweenMinMax($key, $value)/*{{{*/
    {
        $dbHandle   =   self::mdHandle($key);
        if (empty($dbHandle))   return  FALSE;

        $dbSql      =   self::getSentenceForModifyMood($value);
        $result     =   $dbHandle->dbExec($dbSql);

        return  $result;
    }/*}}}*/

    public static function save($key, $value)/*{{{*/
    {
        $result =   self::update($key, $value);
        if (empty($result)) $result =   self::insert($key, $value);

        return  $result;
    }/*}}}*/

    private static function getQuerySentence($fields, $orderBy, $start = NULL, $len = NULL)/*{{{*/
    {
        $field  =   ' * ';
        if (!empty($fields))
        {
            if (is_array($fields))
            {
                $field  =   ' `'. implode('`,`', $fields). '` ';
            }
            else
            {
                $field  =   $fields;
            }
        }
        $where  =   Array();
        $where  =   self::getPrimaryKeyConditionArray($where);
        if (isset($where[self::$uuidName])  ||  empty(self::$uuidValue))
        {
            $whereString    =   ' TRUE ';
        }
        else
        {
            #   $whereString    =   self::$uuidName. '="'. self::$uuidValue. '" ';
            $whereString    =   self::$uuidName. "='". self::$uuidValue. "' ";
        }
        $limit  =   NULL;
        if (!is_null($start) && !empty($len))
        {
            $limit  =   ' LIMIT '. intval($start). ','. intval($len);
        }
        $orderByString  =   NULL;
        if (!empty($orderBy))   $orderByString  =   ' ORDER BY '. $orderBy;
        $sql    =   '
                    SELECT '.
                        $field. '
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        $whereString.
                    $orderByString.
                    $limit
                    ;
        return  $sql;
    }/*}}}*/

    private static function getQuerySentenceByBodyid($fields)/*{{{*/
    {
        if (empty($fields)) $fields =   ' * ';
        $sql    =   '
                    SELECT '.
                        $fields. '
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        self::$uuidName. "='". self::$uuidValue. "'
                    LIMIT 1
                    ";
        return  $sql;
    }/*}}}*/

    private static function getQuerySentenceByBodyidWithId($fields)/*{{{*/
    {
        if (empty($fields)) $fields =   ' * ';
        $sql    =   '
                    SELECT '.
            $fields. '
                    FROM '.
            self::$dbName. '.'. self::$tableName. '
                    WHERE '.
            self::$uuidName. "='". intval(self::$uuidValue/1000). "'
                    LIMIT 1
                    ";
        return  $sql;
    }/*}}}*/

    private static function getConditionQuerySentence($fields, $where, $orderBy, $start = NULL, $len = NULL)/*{{{*/
    {
        if (empty($where))  return  self::getQuerySentence($fields, $orderBy, $start, $len);

        $conditionArray =   array();
        $whereString    =   NULL;
        if (is_array($where))
        {
            self::getPrimaryKeyConditionArray($where);
            
            $fields_filter_int = array('uid', 'id', 'bodyId', 'tag_id', 'gid', 'cid');
            
            foreach ($where as  $field  =>  $v)
            {
                if (empty($field))  continue;
                
                if (in_array($field, $fields_filter_int)){
                    $v = intval($v);
                }
                $conditionArray[]   =   '`'. $field. "`='". $v. "'";
            }
            $whereString    =   implode(' AND ', $conditionArray);
        }
        else
        {
            $whereString    =   $where;
            self::getPrimaryKeyConditionString($whereString);
        }
        if (empty($whereString))    return  self::getQuerySentence($fields, $orderBy, $start, $len);

        $field  =   ' * ';
        if (!empty($fields))
        {
            if (is_array($fields))
            {
                $field  =   ' `'. implode('`,`', $fields). '` ';
            }
            else
            {
                $field  =   $fields;
            }
        }
        $limit  =   NULL;
        if (!is_null($start) && !empty($len))
        {
            $limit  =   ' LIMIT '. intval($start). ','. intval($len);
        }
        $orderByString  =   NULL;
        if (!empty($orderBy))   $orderByString  =   ' ORDER BY '. $orderBy;

        $sql    =   '
                    SELECT '.
                        $field. '
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        $whereString.
                    $orderByString.
                    $limit
                    ;
        return  $sql;
    }/*}}}*/

    private static function getCountRowSentence($where)/*{{{*/
    {
        if (empty($where))
        {
            $whereString    =   NULL;
            self::getPrimaryKeyConditionString($whereString);
        }
        elseif (is_array($where))
        {
            self::getPrimaryKeyConditionArray($where);

            $conditionArray             =   array();
            foreach ($where as  $field  =>  $v)
            {
                if (empty($field))  continue;
                $conditionArray[]   =   '`'. $field. "`='". $v. "'";
            }
            $whereString    =   implode(' AND ', $conditionArray);
        }
        else
        {
            $whereString    =   $where;
            self::getPrimaryKeyConditionString($whereString);
        }

        $sql    =   '
                    SELECT
                        count(*) AS num
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getInsertSentence($value)/*{{{*/
    {
        $sql    =   'INSERT INTO '. self::$dbName. '.'. self::$tableName. ' (`'. self::$uuidName. '`) VALUES("'. self::$uuidValue. '")';
        if (is_array($value))
        {
            $fields =   $newValues  =   array();
            foreach ($value as  $field  =>  $newValue)
            {
                if (empty($field))  continue;
                $fields[]   =   '`'. $field. '`';
                $newValues[]=   "'". DOP::replaceData($newValue). "'";
            }
            if (empty($fields)) return  $sql;

            $fieldString=   ' ('. implode(',', $fields). ') ';
            $valueString=   ' ('. implode(',', $newValues). ') ';
            $sql    =   '
                        INSERT INTO '.
                            self::$dbName. '.'. self::$tableName. $fieldString. '
                        VALUES '.
                            $valueString
                        ;
        }

        return  $sql;
    }/*}}}*/
    
    private static function getUpdateSentence($value)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($value)   ||  !is_array($value))  return  $sql;

        $setArray   =   array();
        foreach ($value as  $field  =>  $newValue)
        {
            if (empty($field))  continue;
            $setArray[] =   '`'. $field. "` = '". DOP::replaceData($newValue). "'";
        }
        if (empty($setArray))   return  $sql;

        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(',', $setArray). '
                    WHERE '.
                        self::$uuidName. "='". self::$uuidValue. "'
                    LIMIT 1
                    ";
        return  $sql;
    }/*}}}*/

    private static function getSelectSentenceByKeyid($whereKey, $whereInArray, $addPrimary = true)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($whereKey)    ||  !is_array($whereInArray))   return  $sql;
        if ($whereKey == 'uid') {
            $inString = true;
        } else {
            $inString = false;
        }
	    foreach($whereInArray as $k=>$v){
		    $whereInArray[$k] = $v;
	    }
        if ($inString) {
            $whereString    =   '`'. $whereKey. '` IN (\''. implode('\',\'', $whereInArray). '\')';
        } else {
            $whereString    =   '`'. $whereKey. '` IN ('. implode(', ', $whereInArray). ')';
        }
        if ($addPrimary) {
            self::getPrimaryKeyConditionString($whereString);
        }

        $sql    =   '
                    SELECT * FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getUpdateSentenceByKeyid($value, $whereKey, $whereInArray)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($value)   ||  !is_array($value)   ||  empty($whereKey)    ||  !is_array($whereInArray))   return  $sql;

        $setArray   =   array();
        foreach ($value as  $field  =>  $newValue)
        {
            if (empty($field))  continue;
            $setArray[] =   '`'. $field. "` = '". DOP::replaceData($newValue). "'";
        }
        if (empty($setArray))   return  $sql;
	    foreach($whereInArray as $k=>$v){
		    $whereInArray[$k] = $v;
	    }
        $whereString    =   '`'. $whereKey. '` IN ('. implode(', ', $whereInArray). ')';
        self::getPrimaryKeyConditionString($whereString);

        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(',', $setArray). '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getUpdateConditionSentence($value, $where)/*{{{*/
    {
        if (empty($where))  return  self::getUpdateSentence($value);

        $sql    =   NULL;
        if (empty($value)   ||  !is_array($value))  return  $sql;

        # if where is null ,the call getUpdateSentence()
        $conditionArray =   array();
        $whereString    =   NULL;
        if (is_array($where))
        {
            self::getPrimaryKeyConditionArray($where);

            foreach ($where as  $field  =>  $v)
            {
                if (empty($field))  continue;
                $conditionArray[]   =   '`'. $field. "`='". $v. "'";
            }
            $whereString    =   implode(' AND ', $conditionArray);
        }
        else
        {
            $whereString    =   $where;
            self::getPrimaryKeyConditionString($whereString);
        }
        if (empty($whereString))    return  self::getUpdateSentence($value);

        # if set value is null, return NULL
        $setArray   =   array();
        foreach ($value as  $field  =>  $newValue)
        {
            if (empty($field))  continue;
            $setArray[] =   '`'. $field. "` = '". DOP::replaceData($newValue). "'";
        }
        if (empty($setArray))   return  $sql;

        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(',', $setArray). '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getUpdateComplexSentence($value)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($value)   ||  !is_array($value))  return  $sql;

        $setArray   =   array();
        if (!empty($value['value']) &&  is_array($value))
        {
            foreach ($value['value']    as  $field  =>  $newValue)
            {
                if (empty($field))  continue;
                $setArray[] =   '`'. $field. "` = '". DOP::replaceData($newValue). "'";
            }
        }
        if (!empty($value['autoInc'])   &&  is_array($value['autoInc']))
        {
            foreach ($value['autoInc']  as  $field  =>  $incNum)
            {
                if (empty($field))  continue;
                if (empty($incNum)) $incNum =   1;
                $setArray[] =   '`'. $field. '` = `'. $field. '` + '. $incNum;
            }
        }
        if (empty($setArray))   return  $sql;

        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(',', $setArray). '
                    WHERE '.
                        self::$uuidName. "='". self::$uuidValue. "'
                    LIMIT 1
                    ";
        return  $sql;
    }/*}}}*/

    private static function getRemoveSentence()/*{{{*/
    {
        $sql    =   '
                    DELETE
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        self::$uuidName. "='". self::$uuidValue. "'
                    LIMIT 1
                    ";
        return  $sql;
    }/*}}}*/

    private static function getRemoveSentenceByKeyid($whereKey, $whereInArray)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($whereKey)    ||  !is_array($whereInArray))   return  $sql;
		foreach($whereInArray as $k=>$v){
			$whereInArray[$k] = $v;
		}
        $whereString    =   '`'. $whereKey. '` IN ('. implode(', ', $whereInArray). ')';
        self::getPrimaryKeyConditionString($whereString);

        $sql    =   '
                    DELETE
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getRemoveConditionSentence($where)/*{{{*/
    {
        if (empty($where))  return  self::getRemoveSentence();

        $conditionArray =   array();
        $whereString    =   NULL;
        if (is_array($where))
        {
            self::getPrimaryKeyConditionArray($where);

            foreach ($where as  $field  =>  $v)
            {
                if (empty($field))  continue;
                $conditionArray[]   =   '`'. $field. "`='". $v. "'";
            }
            $whereString    =   implode(' AND ', $conditionArray);
        }
        else
        {
            $whereString    =   $where;
            self::getPrimaryKeyConditionString($whereString);
        }
        if (empty($whereString))    return  self::getRemoveSentence();

        $sql    =   '
                    DELETE
                    FROM '.
                        self::$dbName. '.'. self::$tableName. '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getSentenceForModifyMood($value)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($value['mood']))  $sql;

        $min    =   0;
        $max    =   100;
        $mood   =   $value['mood'];
        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET mood =
                            if ('. $mood .' > '. $min. ',
                                if (mood +('. $mood. ') > '. $max. ', '. $max. ', mood +('. $mood. ')),
                                if (mood +('. $mood. ') < '. $min. ', '. $min. ', mood +('. $mood. ')))
                    WHERE '.
                        self::$uuidName. '="'. self::$uuidValue. '"
                    LIMIT 1
                    ';
    }/*}}}*/

    private static function getLimitUpdateSentence($value)/*{{{*/
    {
        $sql    =   NULL;
        if (empty($value)   ||  !is_array($value))  return  $sql;

        $setArray   =   $whereArray =   array();
        $whereArray[]   =   self::$uuidName. '="'. self::$uuidValue. '" ';
        foreach ($value as  $field  =>  $changeValue)
        {
            if (empty($field)   ||  empty($changeValue))    continue;

            $setArray[] =   ' `'. $field. '` = `'. $field. '` + "'. $changeValue. '" ';

            if ($changeValue >  0)  continue;
            $absValue   =   abs($changeValue);
            $whereArray[]   =   ' '. $field. ' + "'. $changeValue. '"  >= 0 ';
        }
        if (empty($setArray))   return  $sql;
        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(',', $setArray). '
                    WHERE '.
                        implode(' AND ', $whereArray). '
                    LIMIT 1
                    ';
        return  $sql;
    }/*}}}*/

	private static function getSentenceNumValueAdd($value, $where)/*{{{*/
	{
        if (empty($where)) $where = 'TRUE';

        $sql        =   null;
        $setArray   =   array();

        foreach ($value as $field => $addValue)
        {
            if ( $addValue != 0)
                $setArray[]  =  '`' . $field . '` = `' . $field . '` + ( ' . $addValue . ' )';
        }

        if (is_array($where))
        {
            self::getPrimaryKeyConditionArray($where);

            foreach ($where as  $field  =>  $value)
            {
                if (empty($field))  continue;
                $conditionArray[]   =   '`'. $field. '`="'. $value. '"';
            }
            $whereString    =   implode(' AND ', $conditionArray);
        }
        else
        {
            $whereString    =   $where;
            self::getPrimaryKeyConditionString($whereString);
        }

        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(' , ', $setArray). '
                    WHERE '.
                        $whereString
                    ;


        return $sql;
	}/*}}}*/

    private static function getLimitConditionUpdateSentence($value, $where)/*{{{*/
    {
        if (empty($where))  return  self::getLimitUpdateSentence($value);

        $sql    =   NULL;
        if (empty($value)   ||  !is_array($value))  return  $sql;

        $setArray       =   array();
        foreach ($value as  $field  =>  $changeValue)
        {
            if (empty($field)   ||  empty($changeValue))    continue;
            $setArray[] =   ' `'. $field. '` = `'. $field. '` + "'. $changeValue. '" ';
        }
        if (empty($setArray))   return  $sql;

        $whereString    =   NULL;
        if (is_array($where))
        {
            self::getPrimaryKeyConditionArray($where);

            foreach ($where as  $field  =>  $v)
            {
                if (empty($field))  continue;
                $conditionArray[]   =   '`'. $field. "`='". $v. "'";
            }
            $whereString    =   implode(' AND ', $conditionArray);
        }
        else
        {
            $whereString    =   $where;
            self::getPrimaryKeyConditionString($whereString);

        }
        if (empty($whereString))    return  self::getLimitUpdateSentence($value);

        $sql    =   '
                    UPDATE '.
                        self::$dbName. '.'. self::$tableName. '
                    SET '.
                        implode(',', $setArray). '
                    WHERE '.
                        $whereString
                    ;
        return  $sql;
    }/*}}}*/

    private static function getPrimaryKeyConditionArray(&$whereArray)/*{{{*/
    {
        $result =   array();
        if (empty(TableMap::$noPrimaryCondition[self::$mapPrefix])  &&  !empty(self::$uuidValue))
        {
            $whereArray[self::$uuidName]    =   self::$uuidValue;

            #   $count  =   count($whereArray);
            #   if ($count  < 2)    return  $whereArray;

            #   $result =   array_reverse($whereArray);
            #   $whereArray =   $result;
            #   return  $result;
        }
        else
        {
            $result =   array(self::$uuidName   =>  self::$uuidValue);
        }
        return  $result;
    }/*}}}*/

    private static function getPrimaryKeyConditionString(&$whereString)/*{{{*/
    {
        if (empty(TableMap::$noPrimaryCondition[self::$mapPrefix])  &&  !empty(self::$uuidValue))
        {
            if (empty($whereString))    $whereString    =   self::$uuidName. "='". self::$uuidValue. "'";
            else    $whereString    .=  ' AND '. self::$uuidName. "='". self::$uuidValue. "'";
            #   else    $whereString    =   ' '. self::$uuidName. '="'. self::$uuidValue. '" AND '. $whereString;
        }
        return  NULL;
    }/*}}}*/

    private static function mdHandle($key)  /*{{{*/
    {
        $configArray    =   AC::getDbClient($key);
        #   if (empty($configArray['serverStatus']))
        #   {
        #       exit ('DB server is not work! ');
        #       return  FALSE;
        #   }
        if (empty(TableMap::$dbHostConfig[$configArray['clientServer']]))
        {
            exit ('DB server is not exist! ');
            return  FALSE;
        }
        $hostConfig         =   TableMap::$dbHostConfig[$configArray['clientServer']];
        
        if (!empty($hostConfig) && !isset($hostConfig['host'])){
            $hostlist = $hostConfig;
            $hostConfig = '';
            $dbSum         =     count($hostlist);
            $randNum       =     mt_rand(0,$dbSum - 1);
            $hostConfig    =     $hostlist[$randNum];
        }

        self::$uuidName     =   $configArray['uuidName'];
        self::$uuidValue    =   $configArray['uuidValue'];
        self::$dbName       =   $configArray['dbName'];
        self::$tableName    =   $configArray['tableName'];
        self::$mapPrefix    =   $configArray['mapPrefix'];
        $mdHandle           =   new Database();
        $mdHandle->dbConnect($configArray['clientServer'], $hostConfig);

        return  $mdHandle;
    }/*}}}*/

    private static function mdHandleByClient($key)  /*{{{*/
    {
        $configArray    =   AC::getDbClientByClient($key);
        if (empty(TableMap::$dbHostConfig[$configArray['clientServer']]))
        {
            exit ('DB server is not exist! ');
            return  FALSE;
        }
        $hostConfig         =   TableMap::$dbHostConfig[$configArray['clientServer']];

        self::$dbName       =   $configArray['dbName'];
        self::$tableName    =   $configArray['tableName'];
        self::$mapPrefix    =   $configArray['mapPrefix'];
        $mdHandle           =   new Database();
        $mdHandle->dbConnect($configArray['clientServer'], $hostConfig);

        return  $mdHandle;
    }/*}}}*/

    private static function mdHandleByServer($server)  /*{{{*/
    {
        if (empty(TableMap::$dbHostConfig[$server]))
        {
            exit ('DB server is not exist! ');
            return  FALSE;
        }
        $hostConfig =   TableMap::$dbHostConfig[$server];

        $mdHandle   =   new Database();
        $mdHandle->dbConnect($server, $hostConfig);

        return  $mdHandle;
    }/*}}}*/

    private static function mdHandleByBodyid($code, $bodyId, $uuidName)/*{{{*/
    {
        $configArray    =   AC::getDbClientByBodyid($code, $bodyId, $uuidName);

        if (empty(TableMap::$dbHostConfig[$configArray['clientServer']]))
        {
            exit ('DB server is not exist! ');
            return  FALSE;
        }
        $hostConfig         =   TableMap::$dbHostConfig[$configArray['clientServer']];

        self::$uuidName     =   $configArray['uuidName'];
        self::$uuidValue    =   $configArray['uuidValue'];
        self::$dbName       =   $configArray['dbName'];
        self::$tableName    =   $configArray['tableName'];
        self::$mapPrefix    =   $configArray['mapPrefix'];
        $mdHandle           =   new Database();
        $mdHandle->dbConnect($configArray['clientServer'], $hostConfig);

        return  $mdHandle;
    }/*}}}*/
    
}
